<?php

/**
 * this class help to parse email content var and send mail directly using email function or smtp mail base on phpmailer
 */
class EmailHelper {

    /**
     * send mail welcome 
     */
    public static function sendMailAfterActiveAccount($receiptContent) {
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 7')
		->queryRow();
	$url = '<a href="' . SITE_NAME_URL . '">' . SITE_NAME_URL . '</a>';
	$body = str_replace(
		array('[NAME]', '[SITE_NAME]', '[URL]'), array(
	    $receiptContent['name'],
	    settings()->get('site', 'name'),
	    $url
		), $mailTemplate['body']
	);
	self::send($receiptContent['emailReceive'], $mailTemplate['subject'], $body);
    }

    /**
     * send mail for successfull registration
     */
    public static function sendMailResgistration($receiptContent) {
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 1')
		->queryRow();
	$link = '<a href="' . SITE_NAME_URL . 'site/activekey/key/' . $receiptContent['activationKey'] . '">Click here to active your account</a>';
	$url = '<a href="' . SITE_NAME_URL . '">' . SITE_NAME_URL . '</a>';
	$body = str_replace(
		array('[NAME]', '[SITE_NAME]', '[LINK]', '[URL]'), array(
	    $receiptContent['name'],
	    settings()->get('site', 'name'),
	    $link,
	    $url
		), $mailTemplate['body']
	);
	self::send($receiptContent['emailReceive'], $mailTemplate['subject'], $body);
    }

    /**
     * send email using newsletter template
     * @param string $receiver receiver email
     */
    public static function sendNewsletter($receiver) {
	
    }

    /**
     * send mail after custommer click submit contact form
     * @param mix $receiptContent array or object,
     * array('subject' => 'message', 'body' => 'body', 'email' => email, 'phone' => 'phone')
     */
    public static function sendContactRequest($receiptContent) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 10')
		->queryRow();

	if (is_array($receiptContent)) {
	    $body = str_replace(array('[MESSAGE]', '[SENDER]', '[NAME]', '[PHONE]', '[MAILSUBJECT]', '[IP]', '[SITE_NAME]', '[URL]'), array(
		$receiptContent['body'],
		$receiptContent['email'],
		$receiptContent['name'],
		$receiptContent['phone'],
		$receiptContent['subject'],
		$_SERVER['REMOTE_ADDR'],
		'Contact',
		bu()
		    ), $mailTemplate['body']
	    );
	} elseif (is_object($receiptContent)) {
	    $body = str_replace(array('[MESSAGE]', '[SENDER]', '[NAME]', '[PHONE]', '[MAILSUBJECT]', '[IP]', '[SITE_NAME]', '[URL]'), array(
		$receiptContent->body,
		$receiptContent->email,
		$receiptContent->name,
		$receiptContent->phone,
		$receiptContent->subject,
		$_SERVER['REMOTE_ADDR'],
		'Contact',
		bu()
		    ), $mailTemplate['body']
	    );
	} else {
	    //model not valid
	    throw new CHttpException(500, 'receiver MUST be CFormModel or array');
	    return;
	}

	//send mail to admin
	$adminEmail = app()->settings->get('site', 'admin_email');
	self::send($adminEmail, 'Contact message', $body);
    }

    /**
     * send the request password to user email
     * @param type $resceipt
     * @param type $url
     */

    /**
     * send the request password to user email
     * @param type $resceipt
     * @param type $url
     */
    public static function sendForgotPassword($resceipt) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 2')
		->queryRow();

	$body = str_replace(array('[SITE_NAME]', '[USERNAME]', '[EMAIL]', '[NEWPASS]', '[URL]'), array(
	    settings()->get('site', 'name'),
	    $resceipt['username'],
	    $resceipt['email'],
	    $resceipt['pass'],
	    SITE_NAME_URL,
		), $mailTemplate['body']
	);

	self::send($resceipt['email'], $mailTemplate['subject'], $body);
    }

    /**
     * send mail to reveiver
     * @param string $receiver email
     * @param string $subject
     * @param string $body
     */
    public static function send($receipt, $subject, $body = '', $recipientName = '', $sender = '', $attachmentUrl = '') {

	require_once ROOT . '/common/extensions/phpmailer/class.phpmailer.php';
	$setting = app()->settings;
	$adminEmail = $setting->get('site', 'admin_email');
	$message = '
		    <html>
		    <head>
		      <title>' . $subject . '</title>
		    </head>
		    <body>
		      ' . $body . '
		    </body>
		    </html>
		    ';

	$mail = new PHPMailer();

//	$mail->IsSMTP();      // send via SMTP
//	$mail->Host = $Host;
//	$mail->SMTPAuth = true;      // turn on SMTP authentication	
	if ($sender) {
	    $mailFrom = $sender;
	} else {
	    $mailFrom = $adminEmail;
	}
	$mail->From = $mailFrom;
	$mail->FromName = getUserNameByEmail($mailFrom);
	$mail->AddAddress($receipt);

	$mail->WordWrap = 50; // set word wrap
	$mail->Priority = 1;

	$mail->Subject = '[' . settings()->get('site', 'name') . '] - ' . $subject;
	$mail->Body = $message;
	$mail->IsHTML(true);
	if ($attachmentUrl) {
	    $mail->AddAttachment($attachmentUrl);
	}
	return $mail->Send();
    }

    /*
     * send mail that admin have approved user
     */

    public static function sendMailApprove($receiptContent) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 3')
		->queryRow();
	$url = "<a href='" . SITE_NAME_URL . "'>" . SITE_NAME_URL . "</a>";
	$body = str_replace(array('[SITE_NAME]', '[NAME]', '[URL]'), array(
	    settings()->get('site', 'name'),
	    $receiptContent['username'],
	    SITE_NAME_URL
		), $mailTemplate['body']
	);

	self::send($receiptContent['email'], $mailTemplate['subject'], $body);
    }

    /**
     * send mail to user for waiting approvement
     */
    public static function sendMailForWaitingApprove($receiptContent) {
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 4')
		->queryRow();
	$url = '<a href="' . SITE_NAME_URL . '">' . SITE_NAME_URL . '</a>';
	$body = str_replace(
		array('[NAME]', '[SITE_NAME]', '[URL]'), array(
	    $receiptContent['name'],
	    settings()->get('site', 'name'),
	    $url
		), $mailTemplate['body']
	);
	self::send($receiptContent['emailReceive'], $mailTemplate['subject'], $body);
    }

    /**
     * send mail to admin when he have approved some user successfully
     */
    public static function sendToAdminForApproveSuccess($receiptContent) {
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 5')
		->queryRow();
	$url = '<a href="' . SITE_NAME_URL . '">' . SITE_NAME_URL . '</a>';
	$body = str_replace(
		array('[NAME]', '[SITE_NAME]', '[URL]'), array(
	    $receiptContent['username'],
	    settings()->get('site', 'name'),
	    $url
		), $mailTemplate['body']
	);
	$adminEmail = app()->settings->get('site', 'admin_email');
	self::send($adminEmail, $mailTemplate['subject'], $body);
    }

    /**
     * send mail to admin for account approving
     */
    public static function sendToAdminForApprove($receiptContent) {
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 6')
		->queryRow();
	$url = '<a href="' . SITE_NAME_URL . '">' . SITE_NAME_URL . '</a>';
	$profileLink = 'Click <a href="' . BACKEND_SITE_URL . 'user/member/update?id=' . $receiptContent['userId'] . '">here</a> to view profile of "' . $receiptContent['name'] . '"';
	$body = str_replace(
		array('[NAME]', '[SITE_NAME]', '[URL]', '[PROFILE_LINK]'), array(
	    $receiptContent['name'],
	    settings()->get('site', 'name'),
	    $url,
	    $profileLink
		), $mailTemplate['body']
	);
	$adminEmail = app()->settings->get('site', 'admin_email');
	self::send($adminEmail, $mailTemplate['subject'], $body);
    }

}

